/**
 * 调试网络客户端 - 使用axios实现 (import版本)
 *
 * 使用方式：
 * 1. 复制此文件到您的项目中
 * 2. 安装axios: npm install axios
 * 3. 修改 serverUrl 为您的调试面板地址
 * 4. 在App中导入: import './utils/debugClient'
 * 5. 使用: global.$debug.info('Hello World')
 */

// 注意：这里需要您的项目支持ES6模块导入
import axios from 'axios'

class DebugClient {
  constructor(config = {}) {
    this.config = {
      serverUrl: 'http://10.240.20.130:3000', // 修改为您的调试面板IP地址
      enabled: typeof __DEV__ !== 'undefined' ? __DEV__ : true, // 开发环境启用
      timeout: 10000, // 请求超时时间(10秒)
      retryCount: 2, // 重试次数
      retryDelay: 1000, // 重试延迟
      ...config,
    }

    // 创建axios实例
    this.axiosInstance = axios.create({
      baseURL: this.config.serverUrl,
      timeout: this.config.timeout,
      headers: {
        'Content-Type': 'application/json',
      },
    })

    // 添加请求拦截器
    this.axiosInstance.interceptors.request.use(
      (config) => {
        return config
      },
      (error) => {
        console.warn('📡 Debug request error:', error.message)
        return Promise.reject(error)
      },
    )

    // 添加响应拦截器
    this.axiosInstance.interceptors.response.use(
      (response) => {
        return response
      },
      (error) => {
        console.warn('📡 Debug response error:', error.message)
        return Promise.reject(error)
      },
    )

    // 初始化计时器
    this._timers = new Map()

    // 输出初始化信息
    if (this.config.enabled) {
      console.log('🚀 DebugClient initialized:', this.config.serverUrl)
    }
  }

  /**
   * 发送日志到远程调试面板（带重试机制）
   */
  async _sendLog(level, messages, retryCount = 0) {
    if (!this.config.enabled) return

    try {
      const logData = {
        type: 'log',
        timestamp: Date.now().toString(),
        data: {
          id: Date.now() + Math.random(),
          timestamp: Date.now().toString(),
          level,
          message: messages.map((msg) => {
            if (typeof msg === 'object') {
              try {
                return JSON.stringify(msg, null, 2)
              } catch (e) {
                return String(msg)
              }
            }
            return String(msg)
          }),
          environment: this._getEnvironment(),
          userAgent: this._getUserAgent(),
        },
      }

      // 使用axios发送到调试面板
      await this.axiosInstance.post('/api/log', logData)

      // 同时输出到本地控制台（可选）
      // console[level] && console[level]('[DEBUG]', ...messages);
    } catch (error) {
      const errorMsg = error.response?.data?.message || error.message || 'Unknown error'

      // 重试机制
      if (retryCount < this.config.retryCount) {
        console.warn(`📡 Debug log failed, retrying (${retryCount + 1}/${this.config.retryCount}):`, errorMsg)

        // 延迟重试
        setTimeout(() => {
          this._sendLog(level, messages, retryCount + 1)
        }, this.config.retryDelay * (retryCount + 1))
      } else {
        // 最终失败，静默失败不影响业务
        console.warn('📡 Debug log failed22:', errorMsg)
      }
    }
  }

  /**
   * 获取运行环境
   */
  _getEnvironment() {
    if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
      return 'React Native'
    }
    if (typeof window !== 'undefined') {
      return 'Browser'
    }
    if (typeof process !== 'undefined' && process.versions && process.versions.node) {
      return 'Node.js'
    }
    return 'Unknown'
  }

  /**
   * 获取用户代理
   */
  _getUserAgent() {
    if (typeof navigator !== 'undefined') {
      return navigator.userAgent || 'Unknown'
    }
    return 'Unknown'
  }

  // ==================== 基础日志方法 ====================

  debug(...messages) {
    return this._sendLog('debug', messages)
  }

  info(...messages) {
    return this._sendLog('info', messages)
  }

  log(...messages) {
    return this._sendLog('log', messages)
  }

  warn(...messages) {
    return this._sendLog('warn', messages)
  }

  error(...messages) {
    return this._sendLog('error', messages)
  }

  // ==================== 业务场景方法 ====================

  /**
   * 用户行为日志
   */
  userAction(action, details = {}) {
    return this.info(`👤 用户操作: ${action}`, {
      type: 'user_action',
      action,
      details,
      timestamp: new Date().toISOString(),
    })
  }

  /**
   * 页面事件日志
   */
  pageEvent(page, event, extra = {}) {
    return this.info(`📱 ${page} - ${event}`, {
      type: 'page_event',
      page,
      event,
      extra,
      timestamp: new Date().toISOString(),
    })
  }

  /**
   * 网络请求日志
   */
  networkLog(method, url, requestData = null, responseData = null, duration = 0) {
    return this.info(`🌐 ${method.toUpperCase()} ${url}`, {
      type: 'network',
      method: method.toUpperCase(),
      url,
      requestData,
      responseData,
      duration,
      timestamp: new Date().toISOString(),
    })
  }

  /**
   * 错误日志
   */
  errorLog(error, context = '') {
    return this.error(`❌ ${context}`, {
      type: 'error_log',
      message: error.message,
      stack: error.stack,
      context,
      timestamp: new Date().toISOString(),
    })
  }

  /**
   * 性能日志
   */
  performanceLog(operation, duration, details = {}) {
    return this.info(`⚡ 性能: ${operation} (${duration}ms)`, {
      type: 'performance',
      operation,
      duration,
      details,
      timestamp: new Date().toISOString(),
    })
  }

  // ==================== 高级功能 ====================

  /**
   * 表格数据
   */
  table(data, title = 'Table Data') {
    return this.info(`📊 ${title}`, {
      type: 'table',
      data,
      title,
      timestamp: new Date().toISOString(),
    })
  }

  /**
   * 计时开始
   */
  time(label) {
    this._timers.set(label, Date.now())
    return this.debug(`⏱️ Timer '${label}' started`)
  }

  /**
   * 计时结束
   */
  timeEnd(label) {
    const startTime = this._timers.get(label)

    if (startTime) {
      const duration = Date.now() - startTime
      this._timers.delete(label)
      return this.info(`⏱️ Timer '${label}': ${duration}ms`, {
        type: 'timer',
        label,
        duration,
        timestamp: new Date().toISOString(),
      })
    } else {
      return this.warn(`⏱️ Timer '${label}' does not exist`)
    }
  }

  /**
   * 清空远程日志
   */
  async clear() {
    if (!this.config.enabled) return

    try {
      await this.axiosInstance.post('/api/log', {
        type: 'clear',
        timestamp: Date.now().toString(),
        data: { action: 'clear' },
      })

      console.log('🧹 Remote logs cleared')
    } catch (error) {
      console.warn('📡 Clear logs failed:', error.message)
    }
  }

  /**
   * 测试连接
   */
  async testConnection() {
    try {
      await this.axiosInstance.post('/api/log', {
        type: 'log',
        timestamp: Date.now().toString(),
        data: {
          id: Date.now(),
          timestamp: Date.now().toString(),
          level: 'info',
          message: ['🔗 Debug connection test'],
        },
      })

      console.log('✅ Debug connection successful')
      return true
    } catch (error) {
      console.warn('❌ Debug connection failed:', error.message)
      return false
    }
  }

  /**
   * 更新配置
   */
  updateConfig(newConfig) {
    this.config = { ...this.config, ...newConfig }

    // 更新axios实例配置
    this.axiosInstance.defaults.baseURL = this.config.serverUrl
    this.axiosInstance.defaults.timeout = this.config.timeout

    if (this.config.enabled) {
      console.log('🔧 DebugClient config updated:', this.config)
    }
  }

  /**
   * 获取状态
   */
  getStatus() {
    return {
      enabled: this.config.enabled,
      serverUrl: this.config.serverUrl,
      environment: this._getEnvironment(),
      userAgent: this._getUserAgent(),
    }
  }
}

// 创建全局实例
const $debug = new DebugClient()

// 挂载到全局
if (typeof global !== 'undefined') {
  global.$debug = $debug
} else if (typeof window !== 'undefined') {
  window.$debug = $debug
}

// ES6导出
export default $debug

// 初始化测试
if ($debug.config.enabled) {
  setTimeout(() => {
    $debug.info('🚀 DebugClient ready', {
      environment: $debug._getEnvironment(),
      serverUrl: $debug.config.serverUrl,
    })
  }, 100)
}

